﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SQLDataTransferer.Common.Dialogs
{
    /// <summary>
    /// Interaction logic for ExceptionDialog.xaml
    /// </summary>
    public partial class ExceptionDialog : Window
    {
        #region Events and Delegates

        private delegate void HandleExceptionDelegate(Exception ex, UIElement ctrl, bool closePage);

        #endregion

        #region Constructor(s)

        public ExceptionDialog()
            : this(null) { }

        public ExceptionDialog(Exception ex)
        {
            this.InitializeComponent();

            this.InitializeControls(ex);
        }

        private ExceptionDialog(string message, string stackTrace)
            : this(null)
        {
            this.cboExceptions.Text = "Fout";
            this.txtMessage.Text = message;
            this.txtStackTrace.Text = stackTrace;

        }

        #endregion

        #region Methods

        #region Public

        public static void HandleException(Exception ex, UIElement ctrl)
        {
            HandleException(ex, ctrl, false);
        }

        public static void HandleException(Exception ex, UIElement ctrl, bool closePage)
        {
            if (!ctrl.Dispatcher.CheckAccess())
            {
                ctrl.Dispatcher.Invoke(new HandleExceptionDelegate(HandleException), ex, ctrl, closePage);
                return;
            }

            Dialogs.ExceptionDialog.Show(ex, ctrl);
        }

        public static void Show(Exception ex, UIElement ctrl)
        {
            ExceptionDialog dlg = new ExceptionDialog(ex);
            dlg.Owner = ctrl as Window;
            dlg.ShowDialog();
        }

        #endregion

        #region Private

        private void InitializeControls(Exception ex)
        {
            while (ex != null)
            {
                this.cboExceptions.Items.Add(ex);
                ex = ex.InnerException;
            }

            bool hasItems = this.cboExceptions.Items.Count > 0;

            if (hasItems)
                this.cboExceptions.SelectedIndex = cboExceptions.Items.Count - 1;

            this.cboExceptions.Visibility = hasItems && cboExceptions.Items.Count == 1 ?
                 System.Windows.Visibility.Collapsed :
                 System.Windows.Visibility.Visible;
        }

        #endregion

        #endregion
    }
}
